import axios, { type Method } from 'axios'
import { useUserStore } from '@/stores/index'
import { showToast } from 'vant'
// import router from '@/router'
import { useRouter } from 'vue-router'
const router = useRouter()
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL: 'https://consult-api.itheima.net/',
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user.token}`
    }
    // store.user?.token
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if (res.data.code != 10000) {
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err) => {
    // TODO 5. 处理401错误
    if (err.response.status == 401) {
      showToast('登录过期，请重新登录')
      const store = useUserStore()
      store.delUser()
      router.push({
        path: '/login',
        // router.currentRoute.value.fullPath 当前页面的地址， 因为 从登录页登录成功之后 根据当前地址在跳回来
        // /login?returnUrl='/list'
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

// 类型别名
type Data<T> = {
  code: number
  message: string
  data: T
}
// 二次封装
export const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

export default instance
